package com.example.netty.server;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class MyManager {

    // key: channel id, value: channel
    private final static ConcurrentHashMap<String, Channel> CHANNEL_MAP = new ConcurrentHashMap<>();

    public static void add(String channelId, Channel channel) {
        CHANNEL_MAP.put(channelId, channel);
    }

    public static Channel get(String channelId) {
        return CHANNEL_MAP.get(channelId);
    }

    public static void remove(String channelId) {
        CHANNEL_MAP.remove(channelId);
    }

    public static void send(String channelId, String message) {
        log.info("开始发送消息，channelId:{}, message:{}", channelId, message);
        if (null == channelId) {
            for (Map.Entry<String, Channel> entry : CHANNEL_MAP.entrySet()) {
                entry.getValue().writeAndFlush(new TextWebSocketFrame(message));
            }
        } else {
            Channel channel = get(channelId);
            if (null != channel) {
                channel.writeAndFlush(new TextWebSocketFrame(message));
            }
        }
    }
}
